<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElStep, type FormInstance, type FormRules } from "element-plus";
import { editPasswordService } from "@/api/user";

const ruleFormRef = ref<FormInstance>();

const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("账号不能为空"));
  } else {
    callback();
  }
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else {
    if (ruleForm.value.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass");
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请确认新密码"));
  } else if (value !== ruleForm.value.pass) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const ruleForm = ref({
  oldPwd: "",
  pass: "",
  checkPass: "",
});

const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  oldPwd: [{ validator: checkAge, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//修改密码函数
const updatePwd = () => {
  ruleFormRef.value.validate( async (v)=>{
    if(v){
        await editPasswordService(ruleForm.value);
        ElMessage.success("修改成功");
        //清空表单
        resetForm(ruleFormRef.value);
    }else{
        ElMessage.error("请按规范填写")
    }
  })
};

//挂载后函数
onMounted(()=>{
  //挂载后清空表单，防止浏览器自动填充
  ruleForm.value.pass='';
  ruleForm.value.checkPass='';
  ruleForm.value.oldPwd='';
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="旧密码：" prop="oldPwd">
      <el-input v-model="ruleForm.oldPwd" />
    </el-form-item>
    <el-form-item label="新密码：" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="确认新密码：" prop="checkPass">
      <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="updatePwd"> 确认修改 </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
